<?php
declare (strict_types=1);

namespace app\index\controller;

use app\common\tool\Result;
use think\facade\View;
use think\exception\ValidateException;
use app\common\model\Address as AddressModel;
use think\Response;

class Address extends Base
{
    public function index(): string
    {
        $param = $this->request->get();
        $type = !empty($param['type']) ? $param['type'] : 'add';
        $tpl = !empty($param['tpl']) ? $param['tpl'] : 'index';
        $map = ['uid' => $this->user->id];
        View::assign([
            'list' => AddressModel::getList($map, false, 'create_time', ['p', 'c', 'd']),
            'type' => $type
        ]);

        return View::fetch($tpl);
    }

    public function add($type = ''): string
    {
        View::assign('type', $type);

        return View::fetch();
    }

    public function edit($id): string
    {
        View::assign('info', AddressModel::where(['id' => $id])->find());

        return View::fetch();
    }

    public function save(): Response
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'Address');
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }

        return Result::fastReturn(AddressModel::add($param, $this->user));
    }

    public function delete(): Response
    {
        $id = $this->request->post('id');

        return Result::fastReturn(AddressModel::edit($id, $this->user));
    }

    public function choice(): Response
    {
        $id = $this->request->post('id');

        return Result::fastReturn(AddressModel::choice($id, $this->user));
    }
}